//
//  EaseConversationListViewController.m
//  ChatDemo-UI3.0
//
//  Created by dhc on 15/6/25.
//  Copyright (c) 2015年 easemob.com. All rights reserved.
//

#import "EaseConversationListViewController.h"

#import "EaseSDKHelper.h"
#import "EaseEmotionEscape.h"
#import "EaseConversationCell.h"
#import "EaseConvertToCommonEmoticonsHelper.h"

//#import "DataBaseEngine.h"

//环信UI
//#define NSEaseLocalizedString(key, comment) [[NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"EaseUIResource" withExtension:@"bundle"]] localizedStringForKey:(key) value:@"" table:nil]
#import "SystemEngine.h"
#define NSEaseLocalizedString(key, comment) \
[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(key, @"")]
@interface EaseConversationListViewController ()
{
    dispatch_queue_t refreshQueue;
}

@end

@implementation EaseConversationListViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self registerNotifications];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self unregisterNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
    EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if ([self.dataArray count] <= indexPath.row) {
        return cell;
    }
     id<IConversationModel> model = [self.dataArray objectAtIndex:indexPath.row];
    if (_dataSource && [_dataSource respondsToSelector:@selector(conversationListViewController:modelForIConversationModel:)]) {
        model=[_dataSource conversationListViewController:self modelForIConversationModel:model];
    }
    cell.model = model;
    
    if (_dataSource && [_dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTitleForConversationModel:)]) {
        NSString *detailStr=[_dataSource conversationListViewController:self latestMessageTitleForConversationModel:model];
        cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:detailStr textFont:cell.detailLabel.font];
    } else {
        NSString *detailStr=[self _latestMessageTitleForConversationModel:model];
        cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:detailStr textFont:cell.detailLabel.font];
    }
    
    if (_dataSource && [_dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTimeForConversationModel:)]) {
        cell.timeLabel.text = [_dataSource conversationListViewController:self latestMessageTimeForConversationModel:model];
    } else {
        cell.timeLabel.text = [self _latestMessageTimeForConversationModel:model];
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [EaseConversationCell cellHeightWithModel:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_delegate && [_delegate respondsToSelector:@selector(conversationListViewController:didSelectConversationModel:)]) {
        EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
        [_delegate conversationListViewController:self didSelectConversationModel:model];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
//        [[EMClient sharedClient].chatManager deleteConversation:model.conversation.conversationId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
//
//        }];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (NSString *)tableView:(UITableView *)tableView  titleForDeleteConfirmationButtonForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return @"delete";
}

#pragma mark - data

-(void)refreshAndSortView
{
    __weak typeof(self) weakself = self;
    if (!refreshQueue) {
        refreshQueue = dispatch_queue_create("com.easemob.conversation.refresh", DISPATCH_QUEUE_SERIAL);
    }
    dispatch_async(refreshQueue, ^{
        if ([weakself.dataArray count] > 1) {
            if ([[weakself.dataArray objectAtIndex:0] isKindOfClass:[EaseConversationModel class]]) {
//                NSArray* sorted = [weakself.dataArray sortedArrayUsingComparator:
//                                   ^(EaseConversationModel *obj1, EaseConversationModel* obj2){
//                                       LKMessage *message1 = [obj1.conversation latestMessage];
//                                       LKMessage *message2 = [obj2.conversation latestMessage];
//
//                                       BOOL isTop1=[[DataBaseEngine sharedDBEngine] isTopOfUserChatHistoryMessageWithUserID:message1.direction==EMMessageDirectionReceive?message1.from:message1.to];
//                                       if (isTop1) {
//                                           return(NSComparisonResult)NSOrderedAscending;
//                                       }
//                                       BOOL isTop2=[[DataBaseEngine sharedDBEngine] isTopOfUserChatHistoryMessageWithUserID:message2.direction==EMMessageDirectionReceive?message2.from:message2.to];
//                                       if (isTop2) {
//                                           return(NSComparisonResult)NSOrderedAscending;
//                                       }
//                                       if(message1.timestamp > message2.timestamp) {
//                                           return(NSComparisonResult)NSOrderedAscending;
//                                       }else {
//                                           return(NSComparisonResult)NSOrderedDescending;
//                                       }
//                                   }];
//                [weakself.dataArray removeAllObjects];
//                [weakself.dataArray addObjectsFromArray:sorted];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.tableView reloadData];
        });
    });
}

- (void )tableViewDidTriggerHeaderRefresh:(void(^)( NSInteger unreadCount))refreshCompletion
{
    __weak typeof(self) weakself = self;
    if (!refreshQueue) {
        refreshQueue = dispatch_queue_create("com.easemob.conversation.refresh", DISPATCH_QUEUE_SERIAL);
    }
    dispatch_async(refreshQueue, ^{
        NSArray *conversations = [[LinkExportClient sharedClient].chatManager getAllConversations];
//        NSArray* sorted = [conversations sortedArrayUsingComparator:
//                           ^(EMConversation *obj1, EMConversation* obj2){
//                               EMMessage *message1 = [obj1 latestMessage];
//                               EMMessage *message2 = [obj2 latestMessage];
//                               BOOL isTop1=[[DataBaseEngine sharedDBEngine] isTopOfUserChatHistoryMessageWithUserID:message1.direction==EMMessageDirectionReceive?message1.from:message1.to];
//                               BOOL isTop2=[[DataBaseEngine sharedDBEngine] isTopOfUserChatHistoryMessageWithUserID:message2.direction==EMMessageDirectionReceive?message2.from:message2.to];
//                               if ((isTop1 && !isTop2) || (!isTop1 && isTop2) ) {
//                                   if (isTop1) {
//                                       return(NSComparisonResult)NSOrderedAscending;
//                                   }
//                                   if (isTop2) {
//                                       return(NSComparisonResult)NSOrderedDescending;
//                                   }
//                               }
//                               if(message1.timestamp > message2.timestamp) {
//                                   return(NSComparisonResult)NSOrderedAscending;
//                               }else {
//                                   return(NSComparisonResult)NSOrderedDescending;
//                               }
//                           }];
//
//
//
//        [weakself.dataArray removeAllObjects];
//        NSInteger unreadCount=0;
//        for (LKConversation *converstion in sorted) {
//            EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:converstion];
//            if (weakself.dataSource && [weakself.dataSource respondsToSelector:@selector(conversationListViewController:modelForIConversationModel:)]) {
//                model = [weakself.dataSource conversationListViewController:weakself
//                                               modelForIConversationModel:model];
//            }
//            if (model) {
//                [weakself.dataArray addObject:model];
//            }
//            unreadCount+=converstion.unreadMessagesCount;
//        }
        
        if (refreshCompletion) {
            dispatch_async(dispatch_get_main_queue(), ^{
//                refreshCompletion(unreadCount);
                refreshCompletion(0);
            });
        }
        [weakself tableViewDidFinishTriggerHeader:YES reload:YES];
    });
}

#pragma mark - EMGroupManagerDelegate

- (void)didUpdateGroupList:(NSArray *)groupList
{
    [self tableViewDidTriggerHeaderRefresh:^(NSInteger unreadCount) {
        
    }];
}

#pragma mark - registerNotifications
-(void)registerNotifications{
//    [self unregisterNotifications];
//    [[LinkExportClient sharedClient].chatManager addDelegate:self];
//    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
//    [[LinkExportClient sharedClient].chatManager removeDelegate];
//    [[EMClient sharedClient].groupManager removeDelegate:self];
}

- (void)dealloc{
    [self unregisterNotifications];
}

#pragma mark - private
- (NSString *)_latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTitle = @"";
    LKMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        LKMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case LKMessageBodyTypeImage:{
                latestMessageTitle = @"图片";
            } break;
            case LKMessageBodyTypeText:{
                NSString *didReceiveText = ((LKTextMessageBody *)messageBody).text;
                latestMessageTitle = didReceiveText;
            } break;
            case LKMessageBodyTypeVoice:{
//                latestMessageTitle = NSEaseLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case LKMessageBodyTypeLocation: {
//                latestMessageTitle = NSEaseLocalizedString(@"message.location1", @"[location]");
            } break;
            case LKMessageBodyTypeVideo: {
//                latestMessageTitle = NSEaseLocalizedString(@"message.video1", @"[video]");
            } break;
            case LKMessageBodyTypeFile: {
//                latestMessageTitle = NSEaseLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}

- (NSString *)_latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    LKMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        double timeInterval = lastMessage.timestamp ;
        if(timeInterval > 140000000000) {
            timeInterval = timeInterval / 1000;
        }
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY/MM/dd"];
        latestMessageTime = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
    }
    return latestMessageTime;
}

@end
